package auth

import (
	"github.com/bgmp/config"
	"github.com/bgmp/handler"
	"github.com/bgmp/model"
	"github.com/bgmp/service"
	"github.com/gin-gonic/gin"
)

func (b Base) LogIn(c *gin.Context, req *LogInRequest) *LogInResponse {
	openid, _, err := service.Code2Session(req.WechatId)
	if err != nil {
		handler.Errorf(c, err.Error())
		return nil
	}
	user, err := model.GetUserByOpenId(openid)
	if err != nil {
		user = &model.User{
			Username: "新用户_" + openid[len(openid)-4:],
			Avatar:   "https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0",
			OpenId:   openid,
			Role:     req.Role,
		}
		err := user.Create(config.DB)
		if err != nil {
			handler.Errorf(c, "创建用户失败")
			return nil
		}
	}
	token, err := service.Sign(user.ID)
	if err != nil {
		handler.Errorf(c, "failed to sign token")
		return nil
	}
	return &LogInResponse{
		Username: user.Username,
		Avatar:   user.Avatar,
		Token:    token,
	}
}

type LogInRequest struct {
	WechatId string `json:"wechatId"`
	Role     int    `json:"role"`
}

type LogInResponse struct {
	Username string `json:"username"`
	Avatar   string `json:"avatar"`
	Token    string `json:"token"`
}
